package org.hbhk.hms.mq.tx.mq;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;

import org.hbhk.hms.mq.tx.provider.MqMessageProvider;
import org.hbhk.hms.mq.tx.provider.MqTxProducer;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;

@SuppressWarnings("all")
public class ClassPathMQScanner extends ClassPathBeanDefinitionScanner {
	private ResourceLoader resourceLoader;
	private Environment environment;

	public ClassPathMQScanner(BeanDefinitionRegistry registry) {
		super(registry);
	}

	/**
	 * 注册包扫描过滤器
	 */
	public void registerFilters() {
		addIncludeFilter(new CombineTypeFilter(MqTxProducer.class, MqMessageProvider.class));

		addExcludeFilter((metadataReader, metadataReaderFactory) -> {
			String className = metadataReader.getClassMetadata().getClassName();
			return className.endsWith("package-info");
		});
	}

	@Override
	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

		if (beanDefinitions.isEmpty()) {
			logger.warn("No MQ Component was found in '" + Arrays.toString(basePackages)
					+ "' package. Please check your configuration.");
		} else {
			processBeanDefinitions(beanDefinitions);
		}

		return beanDefinitions;
	}

	private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
		ScannedGenericBeanDefinition definition;
		for (BeanDefinitionHolder holder : beanDefinitions) {
			definition = (ScannedGenericBeanDefinition) holder.getBeanDefinition();
			if (logger.isDebugEnabled()) {
				logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '"
						+ definition.getBeanClassName() + "' mapperInterface");
			}

			boolean explicitFactoryUsed = false;
			if (!explicitFactoryUsed) {
				if (logger.isDebugEnabled()) {
					logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName()
							+ "'.");
				}
			}
			AnnotationMetadata metadata = definition.getMetadata();
			if (metadata.hasAnnotation(MqTxProducer.class.getName())) {
				String className = definition.getBeanClassName();
				definition.getConstructorArgumentValues().addGenericArgumentValue(className);
				
				definition.setBeanClass(ProducerFactoryBean.class);
				definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
			}
		}
	}

	@Override
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return beanDefinition.getMetadata().isIndependent();
	}

	@Override
	protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) {
		if (super.checkCandidate(beanName, beanDefinition)) {
			return true;
		} else {
			logger.warn(
					"Skipping MapperFactoryBean with name '" + beanName + "' and '" + beanDefinition.getBeanClassName()
							+ "' mapperInterface" + ". Bean already defined with the same name!");
			return false;
		}
	}

	private String resolve(String value) {
		if (StringUtils.hasText(value)) {
			return this.environment.resolvePlaceholders(value);
		}
		return value;
	}

	static class CombineTypeFilter implements TypeFilter {
		private final AnnotationTypeFilter annotationTypeFilter;
		private final AssignableTypeFilter assignableTypeFilter;

		public CombineTypeFilter(Class<? extends Annotation> annotationClass, Class<?> interfaceClass) {
			this.annotationTypeFilter = new AnnotationTypeFilter(annotationClass);
			this.assignableTypeFilter = new AssignableTypeFilter(interfaceClass);
		}

		@Override
		public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
				throws IOException {
			boolean result = annotationTypeFilter.match(metadataReader, metadataReaderFactory)
					&& assignableTypeFilter.match(metadataReader, metadataReaderFactory);
			return result;
		}
	}
}
